<script setup>
import { useBuildingStore } from '@/store/super-manger/buildingStore'
import { storeToRefs } from "pinia";
import { reactive, ref, watch } from 'vue';
import { 
    addBuildingInfoApi, 
    isUsedBuildingApi, 
    getNextBuildingName,
    getEditBuildingInfo,
    submitEditInfo
} from '@/service/buildings'
import { getEditInfoApi } from '@/service/dormitory-manger'
import { throttle } from '@/utils/throttle'
import { showElMessage, showNotifyTip } from '@/utils/showTipMessage'

const buildingStore = useBuildingStore();
const { 
    isShowBuildingPanel, 
    dmData1, 
    dmData2, 
    panelTitle,
    editId,
    openPanelType,
    selectedCount
} = storeToRefs(buildingStore);

// 表单
const ruleFormRef = ref(null);
const form = reactive({
    id: '',
    name: 1,
    desc: '',
    manger1: '',
    manger2: '',
    old_id1: '',
    old_id2: '',
    type: '',
    count: ''
})

// 自定义校验规则
const rules = ref({
    name: [{ required: true, message: '宿舍楼编号不能为空', trigger: 'blur' }],
    desc: [{ required: true, message: '楼栋描述不能为空', trigger: 'blur' }],
    manger1: [{ required: true, message: '请选择第一个管理员', trigger: 'blur' }],
    manger2: [{ required: true, message: '请选择第二个管理员', trigger: 'blur' }],
    type: [{ required: true, message: '请选择楼栋类型', trigger: 'blur' }],
    count: [{ required: true, message: '数量不能为空', trigger: 'change' }],
});

// 添加面板被打开
watch(isShowBuildingPanel, async(newVal) => {
    if (newVal) {   // 打开面板
        // 发送网络请求宿管数据
        buildingStore.getDMData();
        // 将选择的宿管个数置为0
        selectedCount.value = 0;
        if (openPanelType.value === 'add') {    // 通过点击新增按钮打开面板
            addBtnOpen();
        } else if (openPanelType.value === 'edit') {    // 通过编辑按钮打开面板
            editBtnOpen();  
        }
        return;
    }
    resetForm();
})

// 通过点击新增按钮打开面板的处理函数
async function addBtnOpen() {
    // 按顺序获取楼栋编号
    const res = await getNextBuildingName();
    const { nextBuildingName } = res.data.data;
    form.name = nextBuildingName;
}

// 通过编辑按钮打开面板的处理函数
async function editBtnOpen() {
   // 根据id值发送网络请求获取数据
    const res = await getEditBuildingInfo(editId.value);
    const { 
        id,
        building_name,
        building_desc,
        building_mangers1,
        building_mangers2,
        building_type,
        dormitory_count
     } = res.data.data;
    //  根据宿管id获取对应的宿管姓名
    const ids = [building_mangers1, building_mangers2];
    const names = [];
    for (let id of ids) {
        const res = await getEditInfoApi(id);
        names.push(res.data.data.name)
    }

    form.id = id
    form.name = building_name;
    form.desc = building_desc;
    form.manger1 = names[0];
    form.manger2 = names[1];
    form.old_id1 = building_mangers1;
    form.old_id2 = building_mangers2;
    form.type = building_type;
    form.count = dormitory_count;
}

// 管理员1 / 管理员2被选择
const changeSelect = (id) => {
    selectedCount.value++;
   // 请求除了被选择的剩余的管理员
   buildingStore.getDMData(id);
}
watch(selectedCount, (newVal) => {
    if (newVal >= 2) {
        // 发送网络请求
        buildingStore.getDMData([form.manger1, form.manger2]);
    }
})

// 提交表单
const submitForm = async(formEl) => {
    if (!formEl) return;
    await formEl.validate( valid => {
        if (valid) {
            if (openPanelType.value === 'add') {
                 // 发送网络请求
                 const message = '添加宿舍楼成功！'
                handleRequest(addBuildingInfoApi, message);
            } else if (openPanelType.value === 'edit') {
                // 提交编辑信息
                const message = '编辑宿舍楼成功！';
                handleRequest(submitEditInfo, message);
            }
        }
    })
}

// 表单提交网络请求函数
async function handleRequest(fn, message) {
    const res = await fn(form);
    const { code } = res.data;
    if (code === 1) {  // 添加成功
        // 显示提示信息
        isShowBuildingPanel.value = false
        showElMessage(message, false);
        showNotifyTip('新添加的宿舍楼需要【启用】才能使用哦！')
    }
}

// 重置表单
const resetForm = () => {
    const keys = Object.keys(form);
    for (let key of keys) {
        form[key] = ''
    }
}

// 楼栋编号改变
const b_tips = ref('');
const changeNumber = throttle(handleChangeNumber, 300);
async function handleChangeNumber() {
    // 发送网络请求，判断该楼栋编号是否被使用
    const res = await isUsedBuildingApi(form.name);
    if (res.data.code === 1) {
        b_tips.value = res.data.message;
        return;
    }
    b_tips.value = '';
}

</script>

<template>
  <div class="add-panel">
    <el-dialog 
        v-model="isShowBuildingPanel" 
        :title="panelTitle"
        align-center
        :close-on-click-modal="false"
        width="400"
    >
        <el-form 
            :model="form"
            ref="ruleFormRef"
            :rules="rules"
        >
            <el-form-item label="楼栋编号：" prop="name">
                <el-input 
                    v-model="form.name" 
                    placeholder="请输入楼栋数字" 
                    type="number" 
                    @change="changeNumber"
                    :class="b_tips ? 'errorStyle': ''"
                    min="1"
                />
                <transition name="showTips">
                    <template v-if="b_tips">
                        <span class="error_tip">{{ b_tips }}</span>
                    </template>
                </transition>
            </el-form-item>
            <el-form-item label="楼栋描述：" prop="desc">
                <el-input v-model="form.desc" placeholder="请输入楼栋描述" />
            </el-form-item>
            <el-form-item label="管理员1：" prop="manger1">
                <el-select 
                    v-model="form.manger1" 
                    placeholder="请选择管理员1" 
                    @change="changeSelect(form.manger1)"
                >
                    <template v-for="item of dmData1" :key="item.id">
                        <el-option :label="item.name" :value="item.id" />
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item label="管理员2：" prop="manger2">
                <el-select 
                    v-model="form.manger2" 
                    placeholder="请选择管理员2"
                    @change="changeSelect(form.manger2)"
                >
                    <template v-for="item of dmData2" :key="item.id">
                        <el-option :label="item.name" :value="item.id" />
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item label="宿舍楼类型：" prop="type">
                <el-select v-model="form.type" placeholder="请选择宿舍楼类型">
                    <el-option label="男生宿舍楼" value="M" />
                    <el-option label="女生宿舍楼" value="G" />
                    <el-option label="男女混住宿舍楼" value="MIX" />
                </el-select>
            </el-form-item>
            <el-form-item label="宿舍数量：" prop="count">
                <el-input 
                    v-model="form.count" 
                    placeholder="请输入宿舍数量" 
                    type="number" 
                    min="0"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">

                <el-button 
                    type="success" 
                    plain 
                    class="submitBtn" 
                    @click="submitForm(ruleFormRef)"
                >提交</el-button>
                <el-button @click="resetForm()">重置</el-button>
            </div>
        </template>
    </el-dialog>    
  </div>
</template>

<style scoped lang="less">
.el-form-item {
    margin: 25px 0;
    width: 300px;
}
.dialog-footer {
    display: flex;
    .submitBtn {
        flex: 1;
    }
}
</style>